﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace Learning
{
    [Serializable]
    public class PlanarShadowSetting
    {
        public Material shadowMat;
    }

    public class PlanarShadowPass : ScriptableRenderPass
    {
        private Material _material;
        
        private FilteringSettings _filtering;

        private List<ShaderTagId> _shaderTagIdList = new List<ShaderTagId>();
        
        public PlanarShadowPass(Material material)
        {
            renderPassEvent = RenderPassEvent.BeforeRenderingTransparents;
            _material = material;
            
            // 注意绘制队列必须是和材质里的一致
            _filtering = new FilteringSettings(RenderQueueRange.transparent, LayerMask.GetMask("Character"));
            
            _shaderTagIdList.Add(new ShaderTagId("UniversalForward"));
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            DrawingSettings drawingSettings = CreateDrawingSettings(_shaderTagIdList, ref renderingData, renderingData.cameraData.defaultOpaqueSortFlags);
            drawingSettings.overrideMaterial = _material;
            
            context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref _filtering);
        }
    }
    
    public class PlanarShadowFeature : ScriptableRendererFeature
    {
        public PlanarShadowSetting settings = new PlanarShadowSetting();
        
        private PlanarShadowPass _pass;
        
        public override void Create()
        {
            _pass = new PlanarShadowPass(settings.shadowMat);
        }

        public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
        {
            renderer.EnqueuePass(_pass);
        }
    }
}
